Numpy
Introduction to NumPy in Economics
NumPy (Numerical Python) is a fundamental package for scientific computing in Python. Its application in economics is widespread due to its efficient handling of large datasets and its comprehensive mathematical functions. This section explores the utilization of NumPy for basic economic calculations.
Installing and Importing NumPy
Before proceeding with calculations, it is necessary to install and import NumPy:
Creating Arrays for Economic Data
NumPy’s primary object is the homogeneous multidimensional array. In economic contexts, these arrays often represent time series data, price vectors, or matrices of economic indicators.
Basic Statistical Calculations
Economic analysis often requires descriptive statistics to summarize data. NumPy provides functions for essential statistical calculations. Let’s compare NumPy implementations with standard Python implementations:
Mean (Average)
The mean represents the central tendency of a dataset.
Equation: \bar{x} = \frac{1}{n} \sum_{i=1}^n x_i
Standard Python implementation:
103.0
NumPy implementation:
Median
The median is the middle value when a dataset is ordered from least to greatest. It’s useful for understanding the central tendency when data is skewed.
Standard Python implementation:
sorted_prices = sorted(prices)
n = len(sorted_prices)
if n % 2 == 0: # even number
median_price_py = (sorted_prices[n//2 - 1] + sorted_prices[n//2]) / 2
else: # odd number
median_price_py = sorted_prices[n//2]
print(median_price_py)103
NumPy implementation:
Standard Deviation
Standard deviation measures the amount of variation or dispersion of a set of values. In economics, it’s used to quantify the amount of variation or dispersion of a set of data values.
Equation: \sigma = \sqrt{\frac{1}{N} \sum_{i=1}^N (x_i - \bar{x})^2}
Standard Python implementation:
mean = sum(prices) / len(prices)
squared_diff = [
(x - mean) ** 2 for x in prices]
variance = sum(squared_diff) / len(prices)
price_std_py = variance ** 0.5
print(price_std_py)2.0
NumPy implementation (1):
mean = np.sum(prices) / len(prices)
squared_diff = (prices - mean) ** 2
variance = np.sum(squared_diff) / len(prices)
price_std_manual_np = np.sqrt(variance)
print(price_std_manual_np)2.0
NumPy implementation (2):
Comparison and Discussion
As demonstrated, NumPy provides more concise and readable implementations for these statistical calculations. The standard Python implementations require more lines of code and explicit loop constructs.
Key advantages of using NumPy for these calculations include:
Conciseness: NumPy functions like
np.mean(),np.median(), andnp.std()encapsulate complex operations in single function calls.Performance: NumPy operations are implemented in C, making them significantly faster than equivalent Python loops, especially for large datasets.
Precision: NumPy uses optimized algorithms that can provide better numerical stability and precision, particularly for operations like standard deviation on large datasets.
Vectorization: NumPy allows for vectorized operations on entire arrays, which is more efficient and easier to read and maintain than explicit loops.
Consistency: NumPy provides a consistent interface for working with multi-dimensional data, which is particularly useful when dealing with more complex economic datasets.
Time Value of Money Calculations
The time value of money is a core principle in finance and economics. NumPy’s exponential and financial functions facilitate these calculations:
Future Value
Future Value (FV) calculates the value of a current asset at a future date based on an assumed growth rate.
Equation: FV = PV \cdot e^{rt}
Where:
- FV = Future Value
- PV = Present Value
- r = interest rate (as a decimal)
- t = number of time periods
Matrix Operations for Input-Output Analysis
Input-Output analysis in economics often involves matrix operations, which NumPy handles efficiently. This analysis examines the interdependencies between different sectors of the economy.
Leontief Inverse
The Leontief inverse is crucial in input-output analysis. It’s used to compute the total output required to meet a given final demand.
Equation: X = (I - A)^{-1} \cdot D
Where:
- X = Total output vector
- I = Identity matrix
- A = Matrix of technical coefficients
- D = Final demand vector
A = np.array([[0.2, 0.3], [0.4, 0.1]])
D = np.array([[100], [200]])
I = np.eye(A.shape[0])
print('Matrix A')
print(A)
print('\nMatrix D')
print(D)
print('\nMatrix I')
print(I)
print('\n')
print(np.linalg.inv(I - A) @ D)
print(np.matmul(np.linalg.inv(I - A), D))Matrix A
[[0.2 0.3]
[0.4 0.1]]
Matrix D
[[100]
[200]]
Matrix I
[[1. 0.]
[0. 1.]]
[[250. ]
[333.33333333]]
[[250. ]
[333.33333333]]
np.eye(): create an identity matrixA.shape: get the dimension of Anp.linalg: linear algebra module@operator: matrix multiplication, equivalent tonp.matmul(A, B)
Calculating Economic Indicators
NumPy can be used to calculate various economic indicators:
GDP Growth Rate
The GDP growth rate measures how fast the economy is growing. It’s typically calculated on an annual basis.
Equation: \text{GDP Growth Rate} = \frac{\text{GDP}_t - \text{GDP}_{t-1}}{\text{GDP}_{t-1}} \times 100\%
Inflation Rate
The inflation rate measures the rate at which the general level of prices for goods and services is rising, consequently eroding purchasing power.
Equation: \text{Inflation Rate} = \frac{\text{CPI}_t - \text{CPI}_{t-1}}{\text{CPI}_{t-1}} \times 100\%
Optimization Problems
Many economic problems involve optimization. NumPy, in conjunction with SciPy, can solve these problems efficiently.
Cost Minimization (more info.)
This example demonstrates a simple cost minimization problem subject to a constraint.
Objective function: \min f(x) = x_1^2 + x_2^2
Subject to: x_1 + x_2 = 1
from scipy.optimize import minimize
def cost(x):
return x[0]**2 + x[1]**2
def constraint(x):
return x[0] + x[1] - 1
result = minimize(cost, [0.5, 0.5], method='SLSQP',
constraints={'type': 'eq', 'fun': constraint})
print(result) message: Optimization terminated successfully
success: True
status: 0
fun: 0.5
x: [ 5.000e-01 5.000e-01]
nit: 1
jac: [ 1.000e+00 1.000e+00]
nfev: 3
njev: 1